<template>
  <div class="UpdateAuthManage-contianer">
    <BaseBreadcrumb useConvert  v-if="isShow">
      <a-card>
        <a-spin :spinning="loadingState.isNext">
          <a-button
            v-if="!$route.query.pageType"
            type="primary"
            @click="pwdVisible(!GET_PWD)"
          >修改密码</a-button>
          <a-button
            v-if="!$route.query.pageType"
            type="primary"
            class="ml12"
            @click="accountVisible(!GET_ACCOUNT)"
          >修改账号</a-button>
          <a-tabs
            :activeKey="activeKey"
            @tabClick="handleTabClick"
            class="update-auth-manage-tabs"
          >
            <a-tab-pane
              v-for="item in realTabList"
              :key="item.key"
              :tab="item.label"
            >
              <component
                :ref="item.key"
                :is="item.key + 'Info'"
                :pageType="$route.query.pageType"
                :employeeId="routeParms.employeeId || commonChildData.id"
                :userId="routeParms.userId || commonChildData.userId"
                :commonData.sync="commonChildData"
              />
            </a-tab-pane>
          </a-tabs>
          <div class="btns-wrapper">
            <a-button
              type="primary"
              :loading="loadingState.isNext"
              @click="handleNext()"
              v-show="activeKey !== realTabList[realTabList.length - 1].key"
            >下一步</a-button>
          </div>
        </a-spin>
      </a-card>
      <div class="tool-btns page-btn-right-top">
        <a-button
          type="primary"
          :loading="loadingState.isSubmit"
          @click="handleSubmit"
          v-if="pageType !== 'look' && !$route.meta.isPim"
          v-show="submitBtnkeys.includes(activeKey)"
        >提交</a-button>
        <a-button
          v-if="!$route.meta.isPim"
          class="ml12"
          type="primary"
          @click="handleClose"
        >关闭</a-button>
      </div>
    </BaseBreadcrumb>
  </div>
</template>

<script>
import BasicInfo from './updateComponents/BasicInfo'
import JobInfo from './updateComponents/JobInfo'
import SignInfo from './updateComponents/SignInfo'
import AuthInfo from './updateComponents/AuthInfo/index.vue'
import Vue from 'vue'
import { mapGetters } from 'vuex'
import { mapActions } from 'vuex'

const tabsList = [
  {
    label: '基本信息',
    key: 'Basic'
  },
  {
    label: '岗位信息',
    key: 'Job'
  },
  {
    label: '签字信息',
    key: 'Sign'
  },
  {
    label: '权限信息',
    key: 'Auth'
  }
]
export default {
  name: 'UpdateAuthManage' +  new Date(),
  components: {
    BasicInfo,
    JobInfo,
    SignInfo,
    AuthInfo
  },
  data() {
    return {
      submitBtnkeys: ['Basic', 'Job', 'Sign', 'Auth'], // 显示提交按钮的tab页面的key值集合
      commonChildData: {},
      isShow: false,
      tabsList,
      activeKey: 'Basic',
      loadingState: {
        isNext: false,
        isSubmit: false
      },
      // 用户信息
      userInfo: Vue.getAcloudProvider().getUserInfo()
    }
  },
  watch: {
    '$route': {
      handler(val) {
        if (val.name === 'pim' || val.name === 'UpdateAuthManageByUser'){
          this.isShow = false
          const timer = setTimeout(() => {
            this.isShow = true
            clearTimeout(timer)
          })
        }
      },
      deep: true,
      immediate: true
    }
  },
  computed: {
    ...mapGetters(['GET_PWD', 'GET_ACCOUNT']),
    realTabList() {
      return this.tabsList.filter((item) => {
        // 如果是公司用户页面，仅在查看时显示权限tab,个人信息管理pim
        if (this.$route.meta.isUser && this.pageType !== 'look' && !this.$route.meta.isPim) {
          return item.key !== 'Auth'
        }
        return true
      })
    },
    pageType() {
      return this.$route.query.pageType || 'add'
    },
    // 员工id,当pim是获取当前登录人否则从路由获取
    routeParms() {
      return {
        employeeId: this.$route.meta.isPim ? this.userInfo.employee.id : this.$route.query.id,
        userId: this.$route.meta.isPim ? this.userInfo.employee.userId : this.$route.query.userId,
      }
    }
  },
  methods: {
    ...mapActions(['pwdVisible', 'accountVisible']),
    handleSubmit() {
      if (this.loadingState.isSubmit) return
      this.loadingState.isSubmit = true
      const validMap = {
        Basic: this.validateBasicInfo,
        Sign: this.validateSignInfo
      }
      const p = new Promise((resolve, reject) => {
        // 由于所有tab页都需要显示提交按钮，因此对于不需要调接口的tab页，直接弹出成功提示即可
        if (validMap[this.activeKey]) {
          validMap[this.activeKey](resolve, reject)
        } else {
          this.$message.success('提交成功')
          resolve()
        }
      })
      p.then(() => {
        // 如果是最后一个tab，提交成功之后需要返回列表页
        if (this.activeKey === this.realTabList[this.realTabList.length - 1].key) {
          this.handleClose()
        }
        this.loadingState.isSubmit = false
      }).catch(() => {
        this.loadingState.isSubmit = false
      })
    },
    handleClose() {
      this.$close()
    },
    handleTabClick(key) {
      this.handleNext(key)
    },
    validateSignInfo(...args) {
      this.$refs.Sign[0].handleSubmit(...args)
    },
    validateBasicInfo(...args) {
      this.$refs.Basic[0].handleSubmit(...args)
    },
    /**
     * 点击下一步，跳转之前进行的校验，返回一个Promise
     */
    validBeforeNext(key, options = {}) {
      return new Promise((resolve, reject) => {
        // 查看页面直接校验通过
        if (this.pageType === 'look' || this.$route.meta.isPim) {
          resolve()
          return
        }
        // 在这里对需要校验的tab页，添加处理函数
        const validMap = {
          Basic: this.validateBasicInfo,
          Sign: this.validateSignInfo
        }
        if (validMap[key]) {
          validMap[key](resolve, reject, options)
        } else {
          resolve()
        }
      })
    },
    handleNext(key) {
      try {
        if (this.loadingState.isNext) return
        this.loadingState.isNext = true
        // 当传入key时，说明是点击的tab
        this.validBeforeNext(this.activeKey, { isTab: !!key })
          .then(() => {
            this.loadingState.isNext = false
            if (key) {
              this.activeKey = key
              return
            }
            const index = this.realTabList.findIndex((item) => item.key === this.activeKey)
            if (this.realTabList[index + 1]) {
              this.activeKey = this.realTabList[index + 1].key
            } else {
              this.activeKey = this.realTabList[0].key
            }
          })
          .catch(() => {
            this.loadingState.isNext = false
          })
      } catch (e) {
        console.error(e)
      }
    }
  }
}
</script>

<style lang="less" scoped>
.UpdateAuthManage-contianer {
  .btns-wrapper {
    padding-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
}
.update-auth-manage-tabs{
  overflow: inherit;
}
</style>
